﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Xml;
using AIS2.DataAccess;
using MassIntellect.WorkIt;
using System.Xml.Linq;
using AIS2.Frames;

namespace AIS2
{
	class Program
	{
		static void Main(string[] args)
		{
			
			Console.WindowWidth = 140;

			var log = new Log();
#if !DEBUG
		try
			{  
			log.LogThis("PI_RwLoader", "Запуск в рабочем режиме v{0}.".goFormat(Assembly.GetExecutingAssembly().GetName().Version.ToString(4)));
#else
			log.LogThis("PI_RwLoader", "Запуск в режиме отладки v{0}.".goFormat(Assembly.GetExecutingAssembly().GetName().Version.ToString(4)));
#endif			
			string b = (args != null && args.Length > 0) ? args[0] : @"base.xml";
			Console.Title = "aisReportLoader - {0} - v{1} (Press Ctrl+C for correct halt)".goFormat(b, Assembly.GetExecutingAssembly().GetName().Version.ToString(2));
			IWorkFrame w;
			using (SerializeScope.Create())
				w = Factory.CreateFrame(XElement.Load(b));
			w.State = State.InWork;
			Console.CancelKeyPress += (sender, e) =>
			                          	{
			                          		w.State = State.ShutDown;
			                          		Console.WriteLine("Ctrl+C halting...");
			                          		e.Cancel = true;
			                          	};
			//w.OnLog += log.LogHandler;
			//((WorkGroup)w).Frames.First().OnLog += log.LogHandler;
#if DEBUG
			using (SerializeScope.Create())
				w.Serialize().Save(@"C:\1.xml"); 
#endif
			while (w.IsActive)
			{
				w.Activate();
				Thread.Sleep(20);
			}
			log.LogThis("PI_RwLoader", "Обработка закончена.");
#if !DEBUG
			}
			catch (Exception ex)
			{
			    Console.WriteLine("Работа системы прервана. См. лог.");
			    log.LogThis("PI_RwLoader", "Ошибка обработки {0}.{1}Стэк:{1}{2}", ex.Message, Environment.NewLine, ex.StackTrace);
			}
#endif
		}
	}
}
